import axios, { AxiosRequestConfig } from "axios";
import storage from "./storage";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css';
import browserHistory from "@/router/history";
import store from "@/store";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const request = axios.create({
  baseURL: import.meta.env['VITE_BASE_URL'],
  timeout: 1000 * 30
})

request.interceptors.request.use((config) => {
  const header = config.headers || {}

  if (header.isToken || !header.isToken) {
    const token = (store.getState().userModule as any)?.token
    header['Authorization'] = `Bearer ${token}`

    Object.assign(config, { header })
  }

  NProgress.start()
  return config
}, (error) => {
  Promise.reject(error)
  NProgress.done()
})

request.interceptors.response.use((response: any) => {
  const code = Number(response.data.code) || 200
  const CONTEXT_URL = import.meta.env.VITE_VISIT_CONTEXT_PATH
  console.log('返回状态码：', code)

  if (code === 401) {
    // 登录失效
    storage.sessionStorage.remove('token')
    browserHistory.push(CONTEXT_URL + 'login')

    return Promise.reject(response)
  }
  
  NProgress.done()
  return response.data
}, (error) => {
  NProgress.done()
  return Promise.reject(error)
})

export const axiosGet = (url: string, params: Record<string | number, any> = {}, opts: AxiosRequestConfig = {}): Promise<any> => {
  return request({ method: 'get', url, params: { ...params }, ...opts })
}

export const axiosPost = (url: string, data: Record<string | number, any> = {}, opts: AxiosRequestConfig = {}): Promise<any> => {
  return request({ method: 'post', url, data: { ...data }, ...opts })
}

export const axiosPut = (url: string, data: Record<string | number, any> = {}, opts: AxiosRequestConfig = {}): Promise<any> => {
  return request({ method: 'Put', url, data: { ...data }, ...opts })
}

export const axiosDel = (url: string, data: Record<string | number, any> = {}, opts: AxiosRequestConfig = {}): Promise<any> => {
  return request({ method: 'Delete', url, data: { ...data }, ...opts })
}

export default request